/**
 * 通用通知系统Context
 * 提供统一的通知管理功能，支持多种通知类型和使用场景
 */

import React, { createContext, useContext, useState, useCallback, useRef, useEffect } from 'react';
import { notification as antNotification } from 'antd';
import {
  UniversalNotification,
  NotificationState,
  NotificationManager,
  NotificationType,
  NotificationStatus,
  NotificationPhase,
  NotificationConfig,
  ProgressInfo,
  ErrorInfo,
  StatisticsInfo
} from '../types/notification';

// Context类型定义
interface UniversalNotificationContextType extends NotificationManager {
  notifications: NotificationState[];
  activeNotifications: NotificationState[];
  persistentNotifications: NotificationState[];
  queuedNotifications: NotificationState[];
}

// 创建Context
const UniversalNotificationContext = createContext<UniversalNotificationContextType | undefined>(undefined);

// 默认配置
const DEFAULT_CONFIG: Required<NotificationConfig> = {
  autoClose: false,
  autoCloseDelay: 5000,
  persistent: false,
  showProgress: true,
  showActions: true,
  showTimestamp: true,
  showDuration: false,
  allowDismiss: true,
  displayMode: 'adaptive',
  displayStrategy: 'auto',
  maxWidth: 420,
  priority: 0,
  antNotificationDuration: 4.0, // ant-notification显示时长（第一阶段）
  transitionDelay: 3200, // 过渡到Dynamic Island的延迟（稍早开始过渡）
};

// 存储键名
const STORAGE_KEY = 'universal-notifications';
const STORAGE_VERSION = '1.0.0';

interface UniversalNotificationProviderProps {
  children: React.ReactNode;
  maxNotifications?: number;
  enablePersistence?: boolean;
  enableAntNotification?: boolean;
}

export const UniversalNotificationProvider: React.FC<UniversalNotificationProviderProps> = ({
  children,
  maxNotifications = 10,
  enablePersistence = true,
  enableAntNotification = true,
}) => {
  const [notifications, setNotifications] = useState<NotificationState[]>([]);
  const [isInitialized, setIsInitialized] = useState(false);
  
  // Refs
  const idCounterRef = useRef(0);
  const storageAvailable = useRef(false);

  // 检查本地存储可用性
  useEffect(() => {
    try {
      const testKey = '__storage_test__';
      localStorage.setItem(testKey, 'test');
      localStorage.removeItem(testKey);
      storageAvailable.current = true;
    } catch {
      storageAvailable.current = false;
      console.warn('LocalStorage不可用，通知持久化功能将被禁用');
    }
  }, []);

  // 从本地存储加载通知
  const loadNotificationsFromStorage = useCallback(() => {
    if (!enablePersistence || !storageAvailable.current) return [];

    try {
      const stored = localStorage.getItem(STORAGE_KEY);
      if (!stored) return [];

      const parsed = JSON.parse(stored);
      if (parsed.version !== STORAGE_VERSION) {
        localStorage.removeItem(STORAGE_KEY);
        return [];
      }

      return parsed.notifications || [];
    } catch (error) {
      console.error('加载通知失败:', error);
      localStorage.removeItem(STORAGE_KEY);
      return [];
    }
  }, [enablePersistence]);

  // 保存通知到本地存储
  const saveNotificationsToStorage = useCallback((notificationStates: NotificationState[]) => {
    if (!enablePersistence || !storageAvailable.current) return;

    try {
      const dataToStore = {
        version: STORAGE_VERSION,
        timestamp: Date.now(),
        notifications: notificationStates.map(state => ({
          ...state,
          notification: {
            ...state.notification,
            // 移除不需要持久化的函数和复杂对象
            callbacks: undefined,
            actions: state.notification.actions?.map(action => ({
              ...action,
              action: undefined, // 移除函数引用
            })),
          },
        })),
      };

      localStorage.setItem(STORAGE_KEY, JSON.stringify(dataToStore));
    } catch (error) {
      console.error('保存通知失败:', error);
    }
  }, [enablePersistence]);

  // 清理本地存储
  const clearNotificationStorage = useCallback(() => {
    if (!storageAvailable.current) return;
    try {
      localStorage.removeItem(STORAGE_KEY);
    } catch (error) {
      console.error('清理通知存储失败:', error);
    }
  }, []);

  // 初始化时从本地存储恢复通知
  useEffect(() => {
    if (isInitialized) return;

    const storedNotifications = loadNotificationsFromStorage();
    if (storedNotifications.length > 0) {
      setNotifications(storedNotifications);
    }

    setIsInitialized(true);
  }, [loadNotificationsFromStorage, isInitialized]);

  // 持久化通知状态到本地存储
  useEffect(() => {
    if (!isInitialized || !enablePersistence) return;

    const importantNotifications = notifications.filter(state =>
      state.phase === 'persistent' ||
      (state.notification.status === 'running' && state.notification.type === 'progress') ||
      state.notification.config?.persistent
    );

    if (importantNotifications.length > 0) {
      saveNotificationsToStorage(importantNotifications);
    } else {
      clearNotificationStorage();
    }
  }, [notifications, isInitialized, enablePersistence, saveNotificationsToStorage, clearNotificationStorage]);

  // 生成唯一ID
  const generateId = useCallback(() => {
    idCounterRef.current += 1;
    return `universal-notification-${Date.now()}-${idCounterRef.current}`;
  }, []);

  // 合并配置
  const mergeConfig = useCallback((config?: NotificationConfig): Required<NotificationConfig> => {
    return { ...DEFAULT_CONFIG, ...config };
  }, []);

  // 智能显示策略决策 - 优化版
  const getDisplayStrategy = useCallback((notification: UniversalNotification): NotificationDisplayStrategy => {
    const config = notification.config || {};

    // 如果明确指定了策略，使用指定的策略
    if (config.displayStrategy && config.displayStrategy !== 'auto') {
      return config.displayStrategy;
    }

    // 自动决策逻辑
    const { type, status } = notification;

    // 核心规则：所有持久化通知都使用两阶段生命周期
    if (config.persistent === true) {
      return 'both';
    }

    // 持久化通知类型：两阶段显示（先ant-notification，后Dynamic Island）
    const persistentTypes: NotificationType[] = ['progress', 'task', 'monitoring', 'sync', 'upload', 'download', 'maintenance'];
    if (persistentTypes.includes(type)) {
      return 'both';
    }

    // 长时间运行的状态：两阶段显示
    const longRunningStatuses: NotificationStatus[] = ['running', 'paused', 'pending', 'retrying'];
    if (longRunningStatuses.includes(status)) {
      return 'both';
    }

    // 重要通知类型：两阶段显示，提供更好的用户体验
    const importantTypes: NotificationType[] = ['error', 'warning'];
    if (importantTypes.includes(type)) {
      return 'both';
    }

    // 简单成功和信息通知：仅显示ant-notification（快速消失）
    const simpleTypes: NotificationType[] = ['info', 'success'];
    if (simpleTypes.includes(type) && config.persistent !== true) {
      return 'ant-notification';
    }

    // 默认策略：两阶段显示
    return 'both';
  }, []);

  // 添加通知
  const add = useCallback((notificationData: Omit<UniversalNotification, 'id' | 'startTime' | 'lastUpdate'>) => {
    const id = generateId();
    const now = Date.now();
    const config = mergeConfig(notificationData.config);

    const newNotification: UniversalNotification = {
      ...notificationData,
      id,
      startTime: now,
      lastUpdate: now,
      config,
    };

    // 获取显示策略
    const displayStrategy = getDisplayStrategy(newNotification);

    const newState: NotificationState = {
      notification: newNotification,
      phase: 'initial',
      position: { x: 0, y: 0 },
      isExpanded: false,
      isVisible: displayStrategy === 'dynamic-island' || displayStrategy === 'both',
      zIndex: 1000 + notifications.length,
    };

    // 显示Ant Design通知（第一阶段）
    if (enableAntNotification && (displayStrategy === 'ant-notification' || displayStrategy === 'both')) {
      const antType = newNotification.status === 'error' ? 'error' :
                     newNotification.status === 'warning' ? 'warning' :
                     newNotification.status === 'success' ? 'success' : 'info';

      const antNotificationId = antNotification[antType]({
        message: newNotification.title,
        description: newNotification.description || newNotification.message,
        duration: config.antNotificationDuration,
        placement: 'topRight',
        className: displayStrategy === 'both' ? 'notification-transitioning' : '',
      });
    }

    // 添加到Dynamic Island状态（如果需要）
    if (displayStrategy === 'dynamic-island' || displayStrategy === 'both') {
      // 对于两阶段通知，初始时不可见，等待过渡
      const initialVisibility = displayStrategy === 'both' ? false : true;
      const initialPhase = displayStrategy === 'both' ? 'initial' : 'persistent';

      const stateWithVisibility = {
        ...newState,
        phase: initialPhase as NotificationPhase,
        isVisible: initialVisibility,
      };

      setNotifications(prev => {
        // 限制通知数量，但保护正在运行的重要通知
        const updated = [...prev, stateWithVisibility];
        if (updated.length > maxNotifications) {
          // 优先保留正在运行的同步任务和其他重要通知
          const importantStatuses = ['running', 'pending'];
          const importantTypes = ['sync', 'progress'];

          const sortedNotifications = updated.sort((a, b) => {
            const aImportant = importantStatuses.includes(a.notification.status) ||
                             importantTypes.includes(a.notification.type) ||
                             a.notification.config?.persistent;
            const bImportant = importantStatuses.includes(b.notification.status) ||
                             importantTypes.includes(b.notification.type) ||
                             b.notification.config?.persistent;

            if (aImportant && !bImportant) return -1;
            if (!aImportant && bImportant) return 1;

            // 按时间排序，新的在前
            return b.notification.startTime - a.notification.startTime;
          });

          const result = sortedNotifications.slice(0, maxNotifications);



          return result;
        }
        return updated;
      });

      // 如果是两阶段通知，设置过渡定时器
      if (displayStrategy === 'both') {
        console.log(`🔄 两阶段通知 [${id}]: 第一阶段开始，${config.transitionDelay}ms后开始过渡`);

        setTimeout(() => {
          console.log(`🔄 两阶段通知 [${id}]: 开始过渡动画（第二阶段）`);

          // 开始过渡动画（第二阶段）
          setNotifications(prev => prev.map(state =>
            state.notification.id === id
              ? {
                  ...state,
                  phase: 'transitioning',
                  isVisible: true,
                }
              : state
          ));

          // 过渡动画完成后，设置为持久状态
          setTimeout(() => {
            console.log(`🔄 两阶段通知 [${id}]: 过渡完成，进入持久状态`);

            setNotifications(prev => prev.map(state =>
              state.notification.id === id
                ? { ...state, phase: 'persistent' }
                : state
            ));
          }, 800); // 800ms过渡动画时长

        }, config.transitionDelay);
      }
    }

    // 调用开始回调
    newNotification.callbacks?.onStart?.(id);

    return id;
  }, [generateId, mergeConfig, getDisplayStrategy, notifications.length, maxNotifications, enableAntNotification]);

  // 更新通知
  const update = useCallback((id: string, updates: Partial<UniversalNotification>) => {
    setNotifications(prev => prev.map(state => {
      if (state.notification.id !== id) return state;

      const updatedNotification = {
        ...state.notification,
        ...updates,
        lastUpdate: Date.now(),
      };

      // 调用进度回调
      if (updates.progress && updatedNotification.callbacks?.onProgress) {
        updatedNotification.callbacks.onProgress(id, updates.progress);
      }

      // 调用完成回调
      if (updates.status === 'success' || updates.status === 'completed') {
        updatedNotification.callbacks?.onComplete?.(id, updates.data);
      }

      // 调用错误回调
      if (updates.status === 'error' || updates.status === 'failed') {
        updatedNotification.callbacks?.onError?.(id, updates.error || {
          message: updates.description || '操作失败',
        });
      }

      return {
        ...state,
        notification: updatedNotification,
      };
    }));
  }, []);

  // 移除通知
  const remove = useCallback((id: string) => {
    setNotifications(prev => {
      const notification = prev.find(state => state.notification.id === id);
      if (notification) {
        notification.notification.callbacks?.onDismiss?.(id);
      }
      return prev.filter(state => state.notification.id !== id);
    });
  }, []);

  // 清空所有通知
  const clear = useCallback(() => {
    setNotifications([]);
    clearNotificationStorage();
  }, [clearNotificationStorage]);

  // 获取单个通知
  const get = useCallback((id: string) => {
    return notifications.find(state => state.notification.id === id);
  }, [notifications]);

  // 获取所有通知
  const getAll = useCallback(() => {
    return notifications;
  }, [notifications]);

  // 按类型获取通知
  const getByType = useCallback((type: NotificationType) => {
    return notifications.filter(state => state.notification.type === type);
  }, [notifications]);

  // 按状态获取通知
  const getByStatus = useCallback((status: NotificationStatus) => {
    return notifications.filter(state => state.notification.status === status);
  }, [notifications]);

  // 显示通知
  const show = useCallback((id: string) => {
    setNotifications(prev => prev.map(state =>
      state.notification.id === id
        ? { ...state, isVisible: true }
        : state
    ));
  }, []);

  // 隐藏通知
  const hide = useCallback((id: string) => {
    setNotifications(prev => prev.map(state =>
      state.notification.id === id
        ? { ...state, isVisible: false }
        : state
    ));
  }, []);

  // 展开通知
  const expand = useCallback((id: string) => {
    setNotifications(prev => prev.map(state =>
      state.notification.id === id
        ? { ...state, isExpanded: true }
        : state
    ));
  }, []);

  // 收起通知
  const collapse = useCallback((id: string) => {
    setNotifications(prev => prev.map(state =>
      state.notification.id === id
        ? { ...state, isExpanded: false }
        : state
    ));
  }, []);

  // 转换到头部显示
  const transitionToHeader = useCallback((id: string) => {
    setNotifications(prev => prev.map(state =>
      state.notification.id === id
        ? { ...state, phase: 'persistent' }
        : state
    ));
  }, []);

  // 转换到普通显示
  const transitionToNormal = useCallback((id: string) => {
    setNotifications(prev => prev.map(state =>
      state.notification.id === id
        ? { ...state, phase: 'initial' }
        : state
    ));
  }, []);

  // 暂停所有通知
  const pauseAll = useCallback(() => {
    setNotifications(prev => prev.map(state => ({
      ...state,
      notification: {
        ...state.notification,
        status: state.notification.status === 'running' ? 'paused' : state.notification.status,
      },
    })));
  }, []);

  // 恢复所有通知
  const resumeAll = useCallback(() => {
    setNotifications(prev => prev.map(state => ({
      ...state,
      notification: {
        ...state.notification,
        status: state.notification.status === 'paused' ? 'running' : state.notification.status,
      },
    })));
  }, []);

  // 清理已完成的通知
  const clearCompleted = useCallback(() => {
    setNotifications(prev => prev.filter(state =>
      !['success', 'completed', 'failed', 'error', 'cancelled'].includes(state.notification.status)
    ));
  }, []);

  // 按类型清理通知
  const clearByType = useCallback((type: NotificationType) => {
    setNotifications(prev => prev.filter(state => state.notification.type !== type));
  }, []);

  // 计算派生状态
  const activeNotifications = notifications.filter(state =>
    state.isVisible && state.phase !== 'closed'
  );

  const persistentNotifications = notifications.filter(state =>
    state.phase === 'persistent'
  );

  const queuedNotifications = notifications.filter(state =>
    state.phase === 'initial' && state.isVisible
  );

  const contextValue: UniversalNotificationContextType = {
    notifications,
    activeNotifications,
    persistentNotifications,
    queuedNotifications,
    add,
    update,
    remove,
    clear,
    get,
    getAll,
    getByType,
    getByStatus,
    show,
    hide,
    expand,
    collapse,
    transitionToHeader,
    transitionToNormal,
    pauseAll,
    resumeAll,
    clearCompleted,
    clearByType,
  };

  return (
    <UniversalNotificationContext.Provider value={contextValue}>
      {children}
    </UniversalNotificationContext.Provider>
  );
};

// Hook
export const useUniversalNotification = () => {
  const context = useContext(UniversalNotificationContext);
  if (context === undefined) {
    throw new Error('useUniversalNotification must be used within a UniversalNotificationProvider');
  }
  return context;
};
